package com.yuexunit.mobilenurse.module.SignInput.model.impl;

import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.SignInput.api.SignInputApi;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sign_Single;
import com.yuexunit.mobilenurse.module.SignInput.bean.SignsInput_Data;
import com.yuexunit.mobilenurse.module.SignInput.bean.YXSignsInput;
import com.yuexunit.mobilenurse.module.SignInput.bean.YXSignsSingleInput;
import com.yuexunit.mobilenurse.module.SignInput.model.ISignModel;
import com.yuexunit.mobilenurse.util.ApiUtil;
import com.yuexunit.mobilenurse.util.CreateJson;
import com.yuexunit.mobilenurse.util.ProUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by sslcjy on 16/1/26.
 */
public class SignModel implements ISignModel {

    private SignInputApi api;
    //记录Log
    private final Logger log = ProUtil.getLogger(SignModel.class);

    @Override
    public Observable<ArrayList<Sign_Single>> getBaseTypes(String areaId) {
        api = ApiInstance();
        return api.getBaseTypes(areaId).filter(new Func1<YXSignsSingleInput, Boolean>() {
            @Override
            public Boolean call(YXSignsSingleInput yxSignsInput) {
                log.debug("getBaseTypes_call:"+yxSignsInput.toString());
                return yxSignsInput.getCode() == 200;
            }
        }).map(new Func1<YXSignsSingleInput, ArrayList<Sign_Single>>() {
            @Override
            public ArrayList<Sign_Single> call(YXSignsSingleInput yxSignsInput) {
                return yxSignsInput.getData();
            }
        });
    }

    @Override
    public Observable<ArrayList<SignsInput_Data>> getAllTypes(String areaId) {
        api = ApiInstance();
        return api.getAllTypes(areaId).filter(new Func1<YXSignsInput, Boolean>() {
            @Override
            public Boolean call(YXSignsInput yxSignsInput) {
                log.debug("getAllTypes_call:" + yxSignsInput.toString());
                return yxSignsInput.getCode() == 200;
            }
        }).map(new Func1<YXSignsInput, ArrayList<SignsInput_Data>>() {
            @Override
            public ArrayList<SignsInput_Data> call(YXSignsInput yxSignsInput) {
                return yxSignsInput.getData();
            }
        });
    }

    @Override
    public Observable<String> uploadTypesValue(final Map<String, String> praise) {
        return Observable.create(new Observable.OnSubscribe<Object>() {

            @Override
            public void call(Subscriber<? super Object> subscriber) {
                String result = null;
                Boolean isConnect = true;
                int count = 0;
                Object response = null;

                do {
                String nameSpace = AppConfig.WEB_NAME_SPACE;
                String methodName = AppConfig.WEB_NAME_METHOD;
                String url = AppConfig.WEB_CONTENT_EXEC;

                SoapObject request = new SoapObject(nameSpace, methodName);
                request.addProperty("XmlString", CreateJson.Sign_Json(praise.get("inpNo"),praise.get("timestamp"),praise.get("recorder"),praise.get("signData"),praise.get("timepoint")));
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envelope.bodyOut = request;
                envelope.dotNet = true;
                HttpTransportSE ht =  new HttpTransportSE(url,AppConfig.TIMEOUT);
//                Object response = null;
                try {
                    ht.call(nameSpace + methodName, envelope);
                    response = envelope.getResponse();
                    //记录传输到服务器及传回的数据
                    log.info(CreateJson.LOG_JSON(url+",kmhs_enr_record", "2", praise.get("inpNo")+praise.get("timestamp")+praise.get("recorder")+praise.get("signData")+praise.get("timepoint"), response.toString()));
                    isConnect = false;
                    if (response != null) {
                        JSONObject all, body;
                        try {
                            all = new JSONObject(response.toString());
                            body = all.getJSONObject("body");
                            result = body.getString("response");
                        } catch (JSONException e) {
                            log.error("JSONException:", e);
                            subscriber.onError(e);
                        }
                        if ("null".equals(result))
                        {
                            subscriber.onError(new Exception());
                        }
                    } else {
                        subscriber.onError(new Exception());
                    }

                } catch (Exception e) {
                    count++;
                    log.error("Exception", e);
                    e.printStackTrace();
                    subscriber.onError(e);
                }
                } while (isConnect && count < 5);
                subscriber.onNext(response);
            }
        }).map(new Func1<Object, String>() {
            @Override
            public String call(Object response) {
                return (String) response.toString();
            }
        });
    }

    public SignInputApi ApiInstance() {
        if (api != null) {
            return api;
        } else {
            return ApiUtil.getInstance().createRetrofitApi(SignInputApi.class);
        }
    }

}
